package org.zhtkj.web.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.zhtkj.framework.TCPServer;
import org.zhtkj.framework.TCPServerHandler;
import org.zhtkj.framework.codec.MessageDecoder;
import org.zhtkj.framework.codec.MessageEncoder;
import org.zhtkj.framework.mapping.HandlerMapper;
import org.zhtkj.framework.session.SessionManager;
import org.zhtkj.framework.spring.SpringHandlerMapper;
import org.zhtkj.web.jt808.codec.JT808MessageDecoder;
import org.zhtkj.web.jt808.codec.JT808MessageEncoder;

@Configuration
public class NettyConfig {

	@Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Bean
    public TCPServerHandler tcpServerHandler(MessageDecoder messageDecoder, MessageEncoder<?> messageEncoder, HandlerMapper handlerMapper, RedisTemplate<String, Object> redisTemplate) {
        return new TCPServerHandler(messageDecoder, messageEncoder, handlerMapper, sessionManager(), redisTemplate);
    }
    
    @Bean
    public TCPServer TCPServer() {
    	TCPServerHandler tcpServerHandler = tcpServerHandler(messageDecoder(), messageEncoder(), handlerMapper(), redisTemplate);
        TCPServer server = new TCPServer(7701, tcpServerHandler);
        server.startServer();
        return server;
    }

    @Bean
    public HandlerMapper handlerMapper() {
        return new SpringHandlerMapper("org.zhtkj.web.endpoint");
    }

    @Bean
    public MessageDecoder messageDecoder() {
        return new JT808MessageDecoder(Charsets.GBK);
    }

	@Bean
    public MessageEncoder<?> messageEncoder() {
        return new JT808MessageEncoder(Charsets.GBK);
    }
	
	@Bean
    public SessionManager sessionManager() {
		return new SessionManager(redisTemplate);
	}
}